<template>
  <div class="generate-page">
    <!-- 进度展示区域 -->
    <div class="progress-section">
      <div class="progress-animation">
        <!-- 根据状态显示不同的动画 -->
        <div v-if="currentTask?.status === 'pending'" class="status-pending">
          <van-loading size="40px" color="#6366f1">排队中...</van-loading>
          <p class="status-text">您的任务正在排队中，请稍候</p>
        </div>
        
        <div v-else-if="currentTask?.status === 'processing'" class="status-processing">
          <div class="progress-circle">
            <van-circle
              v-model:current-rate="progressRate"
              :rate="currentTask.progress"
              size="120px"
              color="#6366f1"
              layer-color="#f0f0f0"
              :text="`${currentTask.progress}%`"
            />
          </div>
          <p class="status-text">AI正在为您的猫咪生成创意图片</p>
          <p class="progress-detail">{{ getProgressText() }}</p>
        </div>
        
        <div v-else-if="currentTask?.status === 'completed'" class="status-completed">
          <van-icon name="success" class="success-icon" />
          <p class="status-text">生成完成！</p>
        </div>
        
        <div v-else-if="currentTask?.status === 'failed'" class="status-failed">
          <van-icon name="close" class="error-icon" />
          <p class="status-text">生成失败</p>
          <p class="error-message">{{ currentTask?.error_message || '未知错误' }}</p>
        </div>
      </div>
    </div>

    <!-- 任务信息 -->
    <div class="task-info" v-if="currentTask">
      <div class="info-card">
        <h3 class="card-title">生成信息</h3>
        <div class="info-list">
          <div class="info-item">
            <span class="info-label">选择风格</span>
            <span class="info-value">{{ currentTask.style_template?.name || '未知风格' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">AI模型</span>
            <span class="info-value">{{ currentTask.ai_model || '默认模型' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">图片尺寸</span>
            <span class="info-value">{{ currentTask.width }} × {{ currentTask.height }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建时间</span>
            <span class="info-value">{{ formatTime(currentTask.created_at) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 原图预览 -->
    <div class="original-preview" v-if="currentTask?.original_image_url">
      <h3 class="preview-title">原始照片</h3>
      <div class="image-container">
        <img :src="currentTask.original_image_url" alt="原始图片" />
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <van-button 
        v-if="currentTask?.status === 'completed'"
        type="primary" 
        size="large" 
        block 
        round
        @click="viewResult"
        class="action-btn"
      >
        查看结果
      </van-button>
      
      <van-button 
        v-else-if="currentTask?.status === 'failed'"
        type="primary" 
        size="large" 
        block 
        round
        @click="retryGenerate"
        class="action-btn"
      >
        重新生成
      </van-button>
      
      <van-button 
        v-else
        type="default" 
        size="large" 
        block 
        round
        @click="cancelTask"
        class="action-btn"
      >
        取消任务
      </van-button>
    </div>

    <!-- 温馨提示 -->
    <div class="tips-section">
      <van-notice-bar
        left-icon="volume-o"
        text="生成时间约1-3分钟，请耐心等待。您可以离开此页面，稍后在历史记录中查看结果。"
        background="#fff7e6"
        color="#fa8c16"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useImageStore } from '../stores/image'
import type { ImageTask } from '../types'
import { Toast, Dialog } from 'vant'

const router = useRouter()
const route = useRoute()
const imageStore = useImageStore()

const currentTask = ref<ImageTask | null>(null)
const progressRate = ref(0)
let pollingTimer: NodeJS.Timeout | null = null

// 从路由参数获取任务ID
const taskId = computed(() => route.query.taskId as string)

// 获取进度文本
const getProgressText = () => {
  if (!currentTask.value) return ''
  
  const progress = currentTask.value.progress
  if (progress < 20) return '正在分析图片...'
  if (progress < 40) return '正在处理风格...'
  if (progress < 60) return 'AI正在创作中...'
  if (progress < 80) return '正在优化细节...'
  if (progress < 100) return '即将完成...'
  return '生成完成！'
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 轮询检查任务状态
const startPolling = () => {
  if (pollingTimer) return
  
  pollingTimer = setInterval(async () => {
    if (!taskId.value || !currentTask.value) return
    
    // 如果任务已完成或失败，停止轮询
    if (['completed', 'failed'].includes(currentTask.value.status)) {
      stopPolling()
      return
    }
    
    try {
      const result = await imageStore.getTaskStatus(taskId.value)
      if (result.success) {
        currentTask.value = result.task
        
        // 任务完成时的处理
        if (result.task.status === 'completed') {
          Toast.success('生成完成！')
          stopPolling()
        } else if (result.task.status === 'failed') {
          Toast.fail('生成失败')
          stopPolling()
        }
      }
    } catch (error) {
      console.error('获取任务状态失败:', error)
    }
  }, 2000) // 每2秒检查一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
}

// 查看结果
const viewResult = () => {
  if (currentTask.value?.id) {
    router.push(`/result/${currentTask.value.id}`)
  }
}

// 重新生成
const retryGenerate = () => {
  Dialog.confirm({
    title: '重新生成',
    message: '确定要重新生成图片吗？这将消耗一次生成次数。'
  }).then(() => {
    router.push('/upload')
  })
}

// 取消任务
const cancelTask = () => {
  Dialog.confirm({
    title: '取消任务',
    message: '确定要取消当前生成任务吗？'
  }).then(() => {
    stopPolling()
    router.push('/upload')
  })
}

// 加载任务信息
const loadTask = async () => {
  if (!taskId.value) {
    Toast.fail('任务ID不存在')
    router.push('/upload')
    return
  }
  
  try {
    const result = await imageStore.getTaskStatus(taskId.value)
    if (result.success) {
      currentTask.value = result.task
      
      // 如果任务未完成，开始轮询
      if (!['completed', 'failed'].includes(result.task.status)) {
        startPolling()
      }
    } else {
      Toast.fail(result.error || '加载任务信息失败')
      router.push('/upload')
    }
  } catch (error: any) {
    Toast.fail(error.message || '加载任务信息失败')
    router.push('/upload')
  }
}

onMounted(() => {
  loadTask()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.generate-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.progress-section {
  background: white;
  border-radius: 20px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.progress-animation {
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.status-pending,
.status-processing,
.status-completed,
.status-failed {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.progress-circle {
  margin-bottom: 16px;
}

.status-text {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.progress-detail {
  font-size: 14px;
  color: #666;
}

.success-icon {
  font-size: 80px;
  color: #52c41a;
  background: #f6ffed;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-icon {
  font-size: 80px;
  color: #ff4d4f;
  background: #fff2f0;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-message {
  font-size: 14px;
  color: #ff4d4f;
  margin-top: 8px;
}

.task-info {
  background: white;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.info-card {
  padding: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: #666;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.original-preview {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.preview-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.image-container {
  text-align: center;
}

.image-container img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-section {
  margin-bottom: 20px;
}

.action-btn {
  font-weight: bold;
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
}

.tips-section {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}
</style>